<template>
  <div class="wrap">
    <div class="wrap-button">
      <a-button style="margin-right: 8px" type="primary" @click="showAddRole">新增</a-button>
      <!-- <div style="float: right">
        <a-input
          v-model:value="keyword"
          style="width: 180px; margin-right: 8px"
          placeholder="输入关键字查询"
        >
          <template #prefix>
            <user-outlined />
          </template>
        </a-input>
        <a-button type="primary" @click="handleSearch">查询</a-button>
      </div> -->
    </div>
    <div class="wrap-table">
      <!-- <BaseTitle title="用户列表" /> -->
      <a-table
        :loading="loading"
        :dataSource="data"
        :columns="columns"
        size="middle"
        @change="handleTableChange"
        width="300"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'operation'">
            <a-button
              class="button-interval"
              type="link"
              :icon="h(SettingOutlined)"
              @click="showPermission(record)"
              size="small"
            >
              授权
            </a-button>
            <a-button
              class="button-interval"
              type="link"
              :icon="h(DeleteOutlined)"
              size="small"
              @click="handleDelete(record)"
            >
              删除
            </a-button>
          </template>
        </template>
      </a-table>
      <a-modal v-model:visible="open" title="新增角色" @ok="handleAddSubmit">
        <a-form
          ref="formRef"
          style="margin-top: 24px"
          :model="formState"
          name="basic"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
          autocomplete="off"
        >
          <a-form-item
            label="角色名称"
            name="roleName"
            :rules="[{ required: true, message: 'Please input your roleName!' }]"
          >
            <a-input
              readOnly
              onfocus="this.removeAttribute('readonly');"
              onblur="this.setAttribute('readonly',true);"
              v-model:value="formState.roleName"
            />
          </a-form-item>
          <a-form-item
            label="角色编码"
            name="roleCode"
            :rules="[{ required: true, message: 'Please input your roleCode!' }]"
          >
            <a-input v-model:value="formState.roleCode" />
          </a-form-item>
        </a-form>
      </a-modal>
      <a-modal v-model:visible="openPermission" title="授权菜单" @ok="handlePermissionSubmit">
        <a-tree
          checkable
          :tree-data="routeList"
          :field-names="fieldNames"
          v-model:checkedKeys="checkedKeys"
          :autoExpandParent="true"
        />
      </a-modal>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { h, ref, onMounted, reactive, watch } from 'vue'
  import { DeleteOutlined, SettingOutlined } from '@ant-design/icons-vue'
  import { FormInstance, message } from 'ant-design-vue'
  import type { TreeProps } from 'ant-design-vue'
  // import { BaseTitle } from '/@/components/Title'
  import { listRole, addRole, deleteRole, listPermission, setPermission } from '/@/api/sys/role'
  import { RoleInfo, RolePermissionModel } from '/@/api/sys/model/roleModel'
  import type { AppRouteRecordRaw } from '/@/router/types'
  import { getMenuList } from '/@/api/sys/menu'
  import { Modal } from 'ant-design-vue'

  const open = ref<boolean>(false)
  const openPermission = ref<boolean>(false)
  const loading = ref(false)

  const columns = [
    {
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName',
      align: 'center',
    },
    {
      title: '角色编码',
      dataIndex: 'roleCode',
      key: 'roleCode',
      align: 'center',
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      align: 'center',
      width: 240,
    },
  ]

  let data = ref<RoleInfo[]>([])

  let routeList: AppRouteRecordRaw[] = []

  let checkedKeys = ref<string[]>(['3'])

  const fieldNames: TreeProps['fieldNames'] = {
    key: 'id',
    title: 'name',
  }

  let currRoleId = ref<string>('')

  watch(checkedKeys, () => {
    console.log('checkedKeys', checkedKeys)
  })
  //#endregion

  onMounted(() => {
    list()
  })

  async function list() {
    loading.value = true
    const res = await listRole()
    console.log('res', res)
    data.value = res
    loading.value = false
  }

  function handleTableChange() {}

  //#region 用户

  const formRef = ref<FormInstance>()

  let formState = reactive<RoleInfo>({
    id: '',
    roleName: '',
    roleCode: '',
  })

  const showAddRole = () => {
    open.value = true
    formRef.value?.resetFields()
  }

  const handleAddSubmit = () => {
    formRef.value
      ?.validateFields()
      .then(() => {
        addRole(formState).then(() => {
          message.success('新增成功')
          open.value = false
          list()
        })
      })
      .catch(() => {
        message.error('表单填写错误')
      })
  }

  const handleDelete = (record) => {
    Modal.confirm({
      title: '提示',
      maskClosable: true,
      content: '确定要删除该角色吗？',
      onOk() {
        deleteRole(record.id).then(() => {
          list()
          message.success('删除成功')
        })
      },
      onCancel() {},
    })
  }

  //
  const showPermission = async (record) => {
    routeList = (await getMenuList()) as AppRouteRecordRaw[]
    console.log('routeList', routeList)
    checkedKeys.value = await listPermission(record.id)
    currRoleId.value = record.id
    openPermission.value = true
  }

  const handlePermissionSubmit = async () => {
    console.log(checkedKeys.value)
    const params: RolePermissionModel = {
      roleId: currRoleId.value,
      menus: checkedKeys.value,
    }
    await setPermission(params)
    message.success('设置成功')
    openPermission.value = false
  }

  //#endregion
</script>

<style lang="scss" scoped>
  .wrap {
    &-table {
      margin-top: 16px;
    }
  }
</style>
